package handler

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"video_08_01/api/request"
	"video_08_01/consts"
	"video_08_01/global"
	"video_08_01/internal/model"
	"video_08_01/pkg"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm
	var user model.User

	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err = user.GetOneByMobileUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	if req.Password != req.Repeat {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "两次密码输入不一致",
			"data":    "",
		})
		return
	}

	user.Password = pkg.Md5(req.Password)
	user.Name = req.Name

	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Name,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	user.Mobile = req.Mobile
	err = user.GetOneByMobileUser()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "登陆失败",
			"data":    "",
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
			"data":    "",
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, 3*(24*time.Hour), consts.JWT_KEY)

	global.RDB.Set(context.Background(), fmt.Sprintf("token:%d", token), user, 3*(24*time.Hour))
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	})

}
